<template>
  <div class="box">
    <TableSearch
      :search="state.search"
      @search="onSearch"
      @listenClick="listenClick"
    />
    <div class="table-container">
      <el-table
        class="mytable"
        :data="state.tableData"
        v-bind="$attrs"
        stripe
        style="width: 100%"
        v-loading="false"
        :header-cell-style="{
          background: '#E0E0E0',
          color: '#2B2B2B',
          fontWeight: 500
        }"
      >
        <el-table-column type="index" label="序号" width="66" />

        <el-table-column show-overflow-tooltip label="字典名称">
          <template #default="scope">
            <div>
              {{ scope.row.configValue }}
            </div>
          </template>
        </el-table-column>

        <el-table-column show-overflow-tooltip label="字典类型">
          <template #default="scope">
            <div>
              {{ scope.row.customizeFlag == 0 ? '系统默认' : '企业自定义' }}
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" :width="320">
          <template #default="scope">
            <el-button
              v-if="
                scope.row.customizeFlag == 1 &&
                buttonDisplayOrNot(buttonCodes, 'dataEditBtn')
              "
              class="my-table__btn"
              color="#1962E0"
              size="default"
              plain
              @click="editDictionary(scope.row)"
              type="primary"
            >
              编辑
            </el-button>
            <el-button
              v-if="
                scope.row.customizeFlag == 1 &&
                buttonDisplayOrNot(buttonCodes, 'dataDeleteBtn')
              "
              class="my-table__btn"
              size="default"
              plain
              @click="deleteItem(scope.row)"
              type="danger"
            >
              删除
            </el-button>
            <el-button
              v-if="state?.search?.btn[2]?.hide"
              class="my-table__btn"
              size="default"
              plain
              @click="goUp(scope.$index)"
              type="success"
            >
              上升
            </el-button>
            <el-button
              v-if="state.search.btn[2].hide"
              class="my-table__btn"
              size="default"
              plain
              @click="goDown(scope.$index)"
              type="warning"
            >
              下降
            </el-button>
          </template>
        </el-table-column>

        <template #empty>
          <img
            v-if="themeConfig.primary == '#02AD82'"
            src="../../../assets/noData.png"
            alt=""
          />
          <img
            v-else-if="themeConfig.primary == '#063C74'"
            src="../../../assets/noData3.png"
            alt=""
          />
          <img
            v-else="themeConfig.primary == '#514FC2'"
            src="../../../assets/noData2.png"
            alt=""
          />
        </template>
      </el-table>
    </div>

    <DictionariesDialog
      :dialogVisible="dialogVisible"
      :dialogForm="dialogForm"
      :dialogDetail="dialogDetail"
      @cancel="cancel"
      @submit="submit"
    >
    </DictionariesDialog>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { isEmpty } from 'lodash'
import { ref, reactive, defineAsyncComponent, watch, onMounted } from 'vue'
import {
  dictionaryList,
  deleteDictionary,
  updateSort
} from '/@/api/setting/index'
import { zIndexUp, zIndexDown } from '/@/utils/arrayOperation'
import { Session } from '/@/utils/storage'
import { buttonDisplayOrNot } from '../../../utils/buttonBoolean'
import { getButtonListByRoleApi } from '/@/api/publicApi'
import { storeToRefs } from 'pinia'
import { useThemeConfig } from '/@/stores/themeConfig'
const storesThemeConfig = useThemeConfig()
const { themeConfig } = storeToRefs(storesThemeConfig)
const menu = Session.get('menu')
const buttonCodes = ref<any>([])
const TableSearch = defineAsyncComponent(
  () => import('/@/components/table/search.vue')
)
const DictionariesDialog = defineAsyncComponent(
  () => import('./DictionariesDialog.vue')
)

// 定义父组件传过来的值
const props = defineProps({
  configType: {
    type: String,
    default: ''
  }
})

const dialogVisible = ref<boolean>(false) //弹窗是否出现
const dialogForm = {
  width: '25%',
  title: ''
}
const dialogDetail = ref<any>({})

//定义变量内容
const state = reactive({
  tableData: [],
  param: {
    configType: '',
    keyword: ''
    // type: 1 // 必传参数，分页的不要传
  },
  // 搜索表单，动态生成（传空数组时，将不显示搜索，注意格式）
  search: {
    param: [
      {
        label: '',
        prop: 'keyword',
        placeholder: '可输入名称搜索',
        type: 'input'
      }
    ],
    btn: [
      {
        text: '新增',
        fun: 'addDictionary',
        disable: false,
        loading: false,
        type: 'primary',
        hide(): boolean {
          return false
        },
        btns: buttonCodes.value,
        btnCode: 'dataAddBtn'
      },
      {
        text: '排序',
        fun: 'sort',
        disable: false,
        loading: false,
        type: 'primary',
        hide(): boolean {
          return false
        },
        btns: buttonCodes.value,
        btnCode: 'dataSortBtn'
      },
      {
        text: '确定',
        fun: 'define',
        disable: false,
        loading: false,
        type: 'primary',
        hide: false,
        btns: buttonCodes.value,
        btnCode: 'dataSortBtn'
      }
    ],
    //重置表格
    resets: false
  }
})

// 搜索点击时表单回调
const onSearch = (data: EmptyObjectType) => {
  state.param = Object.assign({}, state.param, { ...data })
  if (isEmpty(state.param.keyword)) {
    state.search.btn[1].hide = true
    state.search.btn[2].hide = false
  } else {
    state.search.btn[1].hide = false
    state.search.btn[2].hide = false
  }

  getTableData()
}

//字典排序点击
const sort = () => {
  state.search.btn[1].hide = false
  state.search.btn[2].hide = true
}

//字典排序确任点击
const define = () => {
  const paramsArr: any = []
  state.tableData.forEach((element: any, index: number) => {
    let object = {
      dataId: element.id,
      sort: index
    }
    paramsArr.push(object)
  })

  updateSort(props.configType, paramsArr).then((res) => {
    if (res.code == 0) {
      state.search.btn[1].hide = true
      state.search.btn[2].hide = false
      ElMessage({ type: 'success', message: '排序成功' })
      getTableData()
    }
  })
}

//新增字典弹框
const addDictionary = () => {
  dialogForm.title = '新增'
  dialogDetail.value = { configType: props.configType }
  dialogVisible.value = !dialogVisible.value
}
//编辑字典弹框
const editDictionary = (row: any) => {
  dialogForm.title = '编辑'
  dialogDetail.value = row
  dialogVisible.value = !dialogVisible.value
}
//删除字典弹框
const deleteItem = (row: any) => {
  ElMessageBox.confirm('是否删除此字典?', '删除字典', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      deleteDictionary(row.id).then((res) => {
        if (res.code == 0) {
          ElMessage({ type: 'success', message: '删除成功' })
          getTableData()
        }
      })
    })
    .catch(() => {
      ElMessage({ type: 'info', message: '已取消' })
    })
}
//排序(上升)
const goUp = (index: any) => {
  zIndexUp(state.tableData, index)
}
//排序(下降)
const goDown = (index: any) => {
  zIndexDown(state.tableData, index)
}

//弹框取消点击
const cancel = () => {
  dialogVisible.value = !dialogVisible.value
}
//弹框确定点击
const submit = () => {
  dialogVisible.value = !dialogVisible.value
  getTableData()
}

//定义方法对象 注意定义的方法 必须在上面已经申明 所以建议objFun申明和 listenClick方法 写在页面最下面
const objFun = {
  addDictionary: addDictionary,
  sort: sort,
  define: define
}
// 监听子级表格  传过来的方法
const listenClick = (name: string, val: any) => {
  objFun[name](val)
}

//刷新列表数据
const getTableData = () => {
  dictionaryList(state.param).then((res) => {
    if (res.code == 0) {
      state.tableData = res.data
    }
  })
}

watch(
  () => props.configType,
  () => {
    state.param.configType = props.configType
    state.param.keyword = ''
    //初始化数据
    state.search.btn[1].hide = true
    state.search.btn[2].hide = false
    state.search.resets = !state.search.resets
    getTableData()
  },
  { immediate: true }
)

onMounted(() => {
  menu.forEach(async (element: any) => {
    if (element.menuUrl == '/setting/Dictionaries') {
      let res = await getButtonListByRoleApi({
        terminalType: 1,
        menuPid: element.id
      })
      res.data.forEach((item: any) => {
        buttonCodes.value.push(item.buttonCode)
      })
    }
  })
})
</script>

<style scoped lang="scss">
.box {
  display: flex;
  flex-direction: column;
}

.table-container {
  margin-top: 10px;
}
</style>
